export function isAndroid() {
  const ua = navigator.userAgent.toLocaleLowerCase()
  return /android/.test(ua)
}

export function isIOS() {
  const ua = navigator.userAgent.toLocaleLowerCase()
  return /iphone/.test(ua)
}

export function getAppVersion() {
  const ua = navigator.userAgent
}

// UA
const userAgentMap = {
  XUEERSI: 'jzh',
  VIPX: 'hs_jzh',
  XIWANG: 'subject_jzh',
}

/**
 * @description: 通过UA判断当前app的名称
 * @return [appName, appValue] || undefined
 */
const getAppNameByUA = () => {
  const ua = navigator.userAgent
  const app = Object.entries(userAgentMap)
    .sort((a, b) => b[1].length - a[1].length)
    .find(([k, v]) => {
      return ua.includes(v)
    })
  return Array.isArray(app) ? app[0] : undefined
}

// jsBridge 相关能力根据ua判断
const currentApp = getAppNameByUA()
const inXesApp = typeof window !== 'undefined' && window.xesApp && !!currentApp

// 判断是不是在安卓app内&是旧版本
const isOldVersion = () => {
  try {
    // 客户端登录
    if (inXesApp && isAndroid()) {
      const deviceInfo = window.xesApp?.deviceInfo() || {}
      const appVersionNumber = Number(JSON.parse(deviceInfo).appVersionNumber)
      return appVersionNumber < 92004
    } else {
      return false
    }
  } catch (error) {
    console.log('error', error)
  }
}

// 小米手机
const isXiaoMi = () => {
  const deviceInfo = window.xesApp?.deviceInfo() || {}
  const deviceName = JSON.parse(deviceInfo).devicename.toLocaleLowerCase()
  const unableSelectVideoArr = ['xiaomi', 'redmi', 'hongmi']
  const isUnableDevice = unableSelectVideoArr.some((item) => {
    return deviceName.indexOf(item) > -1
  })
  return isUnableDevice
}
export { inXesApp, isOldVersion, isXiaoMi }

const isWeChat = () => {
  const ua = navigator.userAgent.toLocaleLowerCase()
  return /micromessenger/.test(ua)
}

export const isMobile = () => {
  const ua = navigator.userAgent
  const ipad = ua.match(/(iPad).*OS\s([\d_]+)/)
  const isIphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/)
  const isAndroid = ua.match(/(Android)\s+([\d.]+)/)
  const isMobile = isIphone || isAndroid
  return !!isMobile
}
